package com.atguigu.srb.core.controller.api;

import com.atguigu.srb.common.util.JwtUtils;
import com.atguigu.srb.common.exception.Assert;
import com.atguigu.srb.common.result.R;
import com.atguigu.srb.common.result.ResponseEnum;
import com.atguigu.srb.core.pojo.vo.LoginVO;
import com.atguigu.srb.core.pojo.vo.RegisterVO;
import com.atguigu.srb.core.pojo.vo.UserInfoVO;
import com.atguigu.srb.core.service.UserInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Api(tags = "会员接口")
@RestController
@RequestMapping("/api/core/userInfo")
public class ApiUserInfoController {
    @Resource
    private UserInfoService userInfoService;

    @Resource
    private RedisTemplate redisTemplate;

    @ApiOperation("会员注册")
    @PostMapping("/register")
    public R register(@RequestBody RegisterVO registerVO){
        String mobile = registerVO.getMobile();
        String password = registerVO.getPassword();
        String code = registerVO.getCode();

        // 判断手机号,密码,验证码是否为空
        Assert.notEmpty(mobile, ResponseEnum.MOBILE_NULL_ERROR);
        Assert.notEmpty(password,ResponseEnum.PASSWORD_NULL_ERROR);
        Assert.notEmpty(code,ResponseEnum.CODE_NULL_ERROR);

        // 校验验证码
        String codeCache = (String) redisTemplate.opsForValue().get("srb:sms:code:" + mobile);
        Assert.equals(code,codeCache,ResponseEnum.CODE_ERROR);

        // 注册
        userInfoService.register(registerVO);
        return R.OK().message("注册成功!");
    }

    @ApiOperation("会员登录")
    @PostMapping("/login")
    public R login(@RequestBody LoginVO loginVO, HttpServletRequest request){
        String mobile = loginVO.getMobile();
        String password = loginVO.getPassword();

        // 判断是否为空
        Assert.notEmpty(mobile,ResponseEnum.MOBILE_NULL_ERROR);
        Assert.notEmpty(password,ResponseEnum.PASSWORD_NULL_ERROR);

        // 获取IP地址
        String ip = request.getRemoteAddr();

        // 调用登录方法
        UserInfoVO userInfoVO = userInfoService.login(loginVO, ip);

        // 这里返回的数据对应前端的response.data.userInfoVO
        return R.OK().data("userInfoVO",userInfoVO);
    }

    @ApiOperation("校验令牌")
    @GetMapping("/checkToken")
    public R checkToken(HttpServletRequest request){
        String token = request.getHeader("token");
        boolean result = JwtUtils.checkToken(token);
        Assert.isTrue(result,ResponseEnum.LOGIN_AUTH_ERROR);
        return R.OK();
    }

    @ApiOperation("手机号是否存在")
    @GetMapping("/isMobileExist/{mobile}")
    public boolean isMobileExist(@PathVariable String mobile){
        return userInfoService.isMobileExist(mobile);
    }

    @ApiOperation("网关鉴权测试")
    @GetMapping("/testGateway")
    public R testGateway(){
        return R.OK().message("网关鉴权测试成功");
    }
}